<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RolesController
 *
 * @author Poh Nean
 */
class RolesController extends PsController
{

	public $layout = 'manage';

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageAgency.Role.Manage'),
					),
						), parent::accessRules());
	}

	public function actionIndex()
	{
		$criteria = new CDbCriteria();
		$criteria->compare('t.type', UserAuthItem::TYPE_ROLE);
		$criteria->addCondition('(t.agency_id IS NULL OR t.agency_id = :agency_id)');
		$criteria->addCondition('t.ps_module_code IS NULL OR EXISTS (SELECT ps_module_code FROM `ps_module_enabled` m WHERE party_id=:agency_party_id AND deleted = 0 AND start_date <= UTC_TIMESTAMP() AND end_date > UTC_TIMESTAMP() AND t.ps_module_code = m.ps_module_code)');
		$criteria->params[':agency_id'] = Yii::app()->user->model->agency_id;		
		$criteria->params[':agency_party_id'] = Yii::app()->user->model->agency->party_id;		
		
		$dataProvider = new CActiveDataProvider('UserAuthItem');
		$dataProvider->setCriteria($criteria);

		$data = array();
		$data['dataProvider'] = $dataProvider;
		$this->render('index', $data);
	}

	public function actionView($role_id = null)
	{
		$role = $this->loadRole($role_id);

		$authManager = Yii::app()->authManager;

		$data = array();
		$data['role'] = $role;
		$data['authManager'] = $authManager;
		$data['authItemGroups'] = $this->getOperations();
		$this->render('view', $data);
	}

	public function actionCreate($role_id = null)
	{
		$authManager = Yii::app()->authManager;
		$newRole = new UserAuthItem('create');

		if (isset($_POST['UserAuthItem'])) {
			$agency = Yii::app()->user->model->agency;

			$newRole->attributes = $_POST['UserAuthItem'];
			$newRole->name = $agency->id . '.' . $newRole->description;
			$newRole->type = UserAuthItem::TYPE_ROLE;
			$newRole->agency_id = Yii::app()->user->model->agency_id;
			$isValid = $newRole->validate();

			if ($isValid) {
				$newRole->save(false);

				if (isset($_POST['operation'])) {
					foreach ($_POST['operation'] as $operation => $enabled) {
						if ($enabled == '1') {
							if (!$authManager->hasItemChild($newRole->name, $operation)) {
								$authManager->addItemChild($newRole->name, $operation);
							}
						} else if ($enabled == '0') {
							if ($authManager->hasItemChild($newRole->name, $operation)) {
								$authManager->removeItemChild($newRole->name, $operation);
							}
						}
					}

					PsSystemMessage::add('Role added', 'success');
					$this->redirect(array('roles/index'));
				}
			}
		}

		if (isset($role_id)) {
			$role = $this->loadRole($role_id);

			$newRole->description = $role->description . ' Copy';
		}

		$data = array();
		$data['role'] = $role;
		$data['newRole'] = $newRole;
		$data['authManager'] = $authManager;
		$data['authItemGroups'] = $this->getOperations();
		$this->render('create', $data);
	}

	public function actionUpdate($role_id)
	{
		$role = $this->loadRole($role_id);
		if ($role->agency_id === null) {
			// system roles cannot be deleted
			PsSystemMessage::add('Default system roles cannot be edited.', 'warning');
			$this->redirect(array('roles/index'));
		} else {
			$authManager = Yii::app()->authManager;

			if (isset($_POST['UserAuthItem'])) {
				$agency = Yii::app()->user->model->agency;

				$role->attributes = $_POST['UserAuthItem'];
				$role->name = $agency->id . '.' . $role->description;
				$role->type = UserAuthItem::TYPE_ROLE;
				$role->agency_id = Yii::app()->user->model->agency_id;
				$isValid = $role->validate();

				if ($isValid) {
					$role->save(false);

					if (isset($_POST['operation'])) {
						foreach ($_POST['operation'] as $operation => $enabled) {
							if ($enabled == '1') {
								if (!$authManager->hasItemChild($role->name, $operation)) {
									$authManager->addItemChild($role->name, $operation);
								}
							} else if ($enabled == '0') {
								if ($authManager->hasItemChild($role->name, $operation)) {
									$authManager->removeItemChild($role->name, $operation);
								}
							}
						}

						PsSystemMessage::add('Role updated', 'success');
						$this->redirect(array('roles/index'));
					}
				}
			}

			$data = array();
			$data['role'] = $role;
			$data['authManager'] = $authManager;
			$data['authItemGroups'] = $this->getOperations();
			$this->render('update', $data);
		}
	}

	public function actionDelete($role_id)
	{
		$role = $this->loadRole($role_id);

		if ($role->agency_id === null) {
			// system roles cannot be deleted
			PsSystemMessage::add('Default system roles cannot be deleted.', 'warning');
		} else {
			if ($role->delete()) {
				PsSystemMessage::add('Role deleted.', 'success');
			} else {
				PsSystemMessage::add('Error deleting role.');
			}
		}
		if (!Yii::app()->request->isAjaxRequest) {
			$this->redirect(array('roles/index'));
		}
	}

	/**
	 * @param type $role_id
	 * @return UserAuthItem
	 * @throws PsPageNotFoundException
	 */
	public function loadRole($role_id)
	{
		$criteria = new CDbCriteria();
		$criteria->compare('t.name', $role_id);
		$criteria->compare('t.type', UserAuthItem::TYPE_ROLE);
		$criteria->addCondition('(t.agency_id IS NULL OR t.agency_id = :agency_id)');
		$criteria->params[':agency_id'] = Yii::app()->user->model->agency_id;

		$authItem = UserAuthItem::model()->find($criteria);
		if ($authItem === null) {
			throw new PsPageNotFoundException();
		}

		return $authItem;
	}

	public function getOperations()
	{
		$criteria = new CDbCriteria();
		$criteria->addInCondition('type', array(1, 0)); // Task or operation
		if (isset($role->agency_id)) {
			$criteria->compare('agency_id', $role->agency_id);
		}
		$operationsOrTasks = UserAuthItem::model()->findAll($criteria);

		// group operations or tasks
		$authItemGroups = array();
		if (!empty($operationsOrTasks)) {
			foreach ($operationsOrTasks as $op) {
				$groupName = substr($op['name'], 0, strpos($op['name'], '.'));

				if (strlen($groupName) > 0) {
					$groupName = preg_replace('/((?:^|[A-Z])[a-z]+)/', " $1", $groupName); // camelcase to space
					$groupName = trim($groupName);

					$authItem = array(
						'name' => $op['name'],
						'description' => $op['description'],
						'agency_id' => $op['agency_id'],
					);

					if ($op->ps_module_code === null || (!empty($op->ps_module_code) && Yii::app()->user->checkModuleAccess($op->ps_module_code))) {
						$authItemGroups[$groupName][] = $authItem;
					}
				}
			}
		}

		return $authItemGroups;
	}

}

?>
